<?php
/**
 * User: Drery
 * Date: 2015/12/17
 * Time: 15:17
 */

namespace backend\controllers;
use backend\models\Permission;
use backend\models\Role;
use Yii;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use yii\web\NotFoundHttpException;

class RoleController extends InitController
{
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Role::find()->where(['!=', 'title', '角色管理']),
            'sort' => [
                'attributes' => [
                    'id' => [
                        'asc' => ['id'=>SORT_ASC],
                        'desc' => ['id'=>SORT_DESC]
                    ]
                ]
            ]
        ]);
        return $this->render('index',[
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionAdd()
    {
        $model = new Role();
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return $this->redirect('index');
            }
        }
        return $this->render('add',[
            'model' => $model
        ]);
    }

    public function actionAccredit()
    {
        $id = Yii::$app->request->get('id');
        $model = Role::find()->where(['id'=>$id])->one();
        if (!$model) {
            throw new NotFoundHttpException;
        }
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            if ($model->accredit()) {
                return $this->redirect('index');
            }
        }
        $model->scenario = 'accredit';
        $permissionIds = Yii::$app->user->identity->getPermissionIds();
        $permissionList = Permission::find()->where(['pid'=>0,'is_deleted'=>0])->andWhere(['in', 'id', $permissionIds])
            ->with(['children' => function (ActiveQuery $query) use ($permissionIds) {
                $query->andWhere(['in', 'id', $permissionIds]);
            }])->orderBy(['arrangement'=>SORT_ASC])->all();
        return $this->render('accredit',[
            'model' => $model,
            'permissionList' => $permissionList
        ]);
    }
}